#!/bin/bash
set -euo pipefail

# -------------------------- 配置参数 --------------------------
NACOS_SERVER="http://127.0.0.1:8848"  # Nacos服务器地址（根据实际部署修改）
SERVICE_NAME="host-registry"          # 服务名（统一标识主机登记服务）
GROUP_NAME="DEFAULT_GROUP"            # 服务分组
LOG_FILE="/var/log/nacos_host_register.log"
# --------------------------------------------------------------

# 日志函数
log() {
    local level="$1"
    local message="$2"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" >> "$LOG_FILE"
}

# 检查依赖
check_deps() {
    local deps="curl jq ip hostname"
    for dep in $deps; do
        if ! command -v "$dep" &> /dev/null; then
            log "ERROR" "缺少工具 '$dep'，请安装：sudo apt install $dep"
            exit 1
        fi
    done
}

# 获取主机核心信息（复用之前的多网卡适配逻辑）
get_host_info() {
    local hostname=$(hostname)
    local os=$(lsb_release -d 2>/dev/null | cut -d: -f2 | sed 's/^[ \t]*//')
    os=${os:-"unknown"}

    # 多网卡适配：获取活跃网卡的IP和MAC（确保绑定同一网卡）
    local EXCLUDE_NICS="lo docker0 veth virbr tun tap"
    local NIC_PRIORITY="enp wlp eth wlan"
    local target_mac=""
    local target_ip=""
    local selected_nic=""

    local active_nics=$(ip link show | grep -B1 "UP" | grep -oE "^[0-9]+: [a-zA-Z0-9_-]+:" | awk -F': ' '{print $2}' | sed 's/:$//')

    for nic in $active_nics; do
        if echo " $EXCLUDE_NICS " | grep -q " $nic "; then
            continue
        fi

        local mac=$(ip link show "$nic" | grep -oE "link/ether [0-9a-f:]{17}" | awk '{print $2}')
        [[ -z "$mac" || "$mac" == "00:00:00:00:00:00" ]] && continue

        local ipv4=$(ip -4 addr show "$nic" | grep -oE "inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | awk '{print $2}' | grep -v "127.0.0.1")
        [[ -n "$ipv4" ]] && target_ip="$ipv4" && break  # 优先用IPv4

        local ipv6=$(ip -6 addr show "$nic" | grep -oE "inet6 [0-9a-f:]+/[0-9]+" | awk '{print $2}' | cut -d/ -f1 | grep -vE "::1|fe80::")
        [[ -n "$ipv6" ]] && target_ip="$ipv6"
    done

    [[ -z "$target_ip" || -z "$mac" ]] && { log "ERROR" "未找到有效IP/MAC"; exit 1; }

    # 输出：hostname|ip|mac|os
    echo "$hostname|$target_ip|$mac|$os"
}

register_to_nacos() {
    local host_info="$1"
    IFS="|" read -r hostname ip mac os <<< "$host_info"

    # 关键：添加认证参数（username 和 password）
    local nacos_username="root"  # Nacos 用户名（默认nacos）
    local nacos_password="cyyj6246"  # Nacos 密码（默认nacos，若修改则替换）

    # Nacos 注册API：附加认证参数
    local register_url="${NACOS_SERVER}/nacos/v1/ns/instance"
    local params="serviceName=${SERVICE_NAME}&groupName=${GROUP_NAME}&ip=${ip}&port=80&metadata=hostname=${hostname},mac=${mac},os=${os}&username=${nacos_username}&password=${nacos_password}"

    # 发送带认证的注册请求
    log "INFO" "注册主机到Nacos（带认证）：$hostname（IP：$ip）"
    local response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Content-Type: application/x-www-form-urlencoded" \
        --data "$params" \
        --max-time 10 \
        "$register_url")

    local http_code=$(echo "$response" | tail -n1)
    local resp_body=$(echo "$response" | head -n -1)

    if [[ "$http_code" -eq 200 && "$resp_body" == "ok" ]]; then
        log "INFO" "注册成功（已认证）"
    else
        log "ERROR" "注册失败（认证相关），状态码：$http_code，响应：$resp_body"
        exit 1
    fi
}

# -------------------------- 主流程 --------------------------
log "INFO" "=== 开始执行Nacos主机登记 ==="

check_deps
host_info=$(get_host_info)
register_to_nacos "$host_info"

log "INFO" "=== 执行完成 ==="
